/**
 * 用户数据访问层
 */

const Logger = require('../utils/logger')

class UserRepository {
  constructor(db) {
    this.db = db
    this.collection = db.collection('users')
    this._ = db.command
  }

  /**
   * 根据账号查询用户（支持用户名、手机号、邮箱）
   */
  async findByAccount(account) {
    try {
      const result = await this.collection
        .where(this._.or([
          { username: account },
          { phone: account },
          { email: account }
        ]))
        .get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('UserRepo', '查询用户失败', error)
      throw error
    }
  }

  /**
   * 根据手机号查询用户
   */
  async findByPhone(phone) {
    try {
      const result = await this.collection.where({ phone }).get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('UserRepo', '根据手机号查询用户失败', error)
      throw error
    }
  }

  /**
   * 根据openid查询用户
   */
  async findByOpenid(openid) {
    try {
      const result = await this.collection.where({ openid }).get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('UserRepo', '根据openid查询用户失败', error)
      throw error
    }
  }

  /**
   * 根据用户名查询用户
   */
  async findByUsername(username) {
    try {
      const result = await this.collection.where({ username }).get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('UserRepo', '根据用户名查询用户失败', error)
      throw error
    }
  }

  /**
   * 根据邮箱查询用户
   */
  async findByEmail(email) {
    try {
      const result = await this.collection.where({ email }).get()
      return result.data.length > 0 ? result.data[0] : null
    } catch (error) {
      Logger.error('UserRepo', '根据邮箱查询用户失败', error)
      throw error
    }
  }

  /**
   * 创建用户
   */
  async create(userData) {
    try {
      const result = await this.collection.add({ data: userData })
      return result._id
    } catch (error) {
      Logger.error('UserRepo', '创建用户失败', error)
      throw error
    }
  }

  /**
   * 更新用户信息
   */
  async update(userId, updateData) {
    try {
      await this.collection.doc(userId).update({ data: updateData })
      return true
    } catch (error) {
      Logger.error('UserRepo', '更新用户失败', error)
      throw error
    }
  }

  /**
   * 更新用户积分
   */
  async updatePoints(userId, points) {
    try {
      await this.collection.doc(userId).update({
        data: {
          points: this._.inc(points)
        }
      })
      return true
    } catch (error) {
      Logger.error('UserRepo', '更新用户积分失败', error)
      throw error
    }
  }
}

module.exports = UserRepository

